package com.mayundev.pa.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mayundev.pa.model.ChatResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ChatResponse;

@Slf4j
public class ResponseConverter {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static ChatResponseEntity processSimpleResponse(ChatResponse springResponse) {
        String content = springResponse.getResult().getOutput().getContent();
        ChatResponseEntity responseEntity = new ChatResponseEntity();
        
        try {
            return objectMapper.readValue(content, ChatResponseEntity.class);
        } catch (JsonProcessingException e) {
            log.debug("Content is not JSON format, using raw text");

            if (content.contains("<think>")) {
                String[] parts = content.split("</think>");
                if (parts.length > 1) {
                    responseEntity.setReasoningContent(parts[0].replace("<think>", ""));
                    responseEntity.setContent(parts[1]);
                } else {
                    responseEntity.setContent(content);
                }
            } else {
                responseEntity.setContent(content);
            }
            return responseEntity;
        }
    }

    public static ChatResponseEntity processStreamResponse(ChatResponse response, boolean[] isThinking) {
        String textContent = response.getResult().getOutput().getContent();
        ChatResponseEntity responseEntity = new ChatResponseEntity();

        if (textContent.contains("<think>")) {
            isThinking[0] = true;
            textContent = textContent.replace("<think>", "");
        }
        if (textContent.contains("</think>")) {
            isThinking[0] = false;
            textContent = textContent.replace("</think>", "");
        }

        if (isThinking[0]) {
            responseEntity.setReasoningContent(textContent);
        } else {
            responseEntity.setContent(textContent);
        }

        return responseEntity;
    }
}
